package com.smartwebee.android.blespp.hospital.account;

import android.content.Intent;
import android.database.DatabaseUtils;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.smartwebee.android.blespp.R;
import com.smartwebee.android.blespp.databinding.ActivityLoginBinding;
import com.smartwebee.android.blespp.eventbusclass.RegisterSucEvent;
import com.smartwebee.android.blespp.hospital.BaseActivity;
import com.smartwebee.android.blespp.hospital.HospitalMainActivity;
import com.smartwebee.android.blespp.http.HttpRequest;
import com.smartwebee.android.blespp.http.RequestInterface;
import com.smartwebee.android.blespp.http.VolleyReqQueue;
import com.smartwebee.android.blespp.resp.BaseResp;
import com.smartwebee.android.blespp.resp.LoginResp;
import com.smartwebee.android.blespp.utils.UIUtils;
import com.smartwebee.android.blespp.utils.Utils;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity implements View.OnClickListener, RequestInterface {
    private ActivityLoginBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        TAG = "LoginActivity";
        requestQueue = VolleyReqQueue.getInstance(this).getRequestQueue();
        initView();
    }

    private void initView() {
        binding.btnBack.setOnClickListener(this);
        binding.btnRegister.setOnClickListener(this);
        binding.btnLogin.setOnClickListener(this);

        initEdit();
        //如果输入合法则自动登录
        if (checkInput()) {
            httpLogin();
        }
    }

    private void initEdit() {
        String cacheData = Utils.getData(this, Utils.LOGIN_DATA);
        if (!TextUtils.isEmpty(cacheData)) {
            LoginResp loginResp = new Gson().fromJson(cacheData, LoginResp.class);
            binding.editNum.setText(loginResp.getData().getSn());
        }
        String pwd = Utils.getData(this, Utils.PWD);
        binding.editPwd.setText(pwd);
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.btn_login:
                if (checkInput()) {
                    httpLogin();
                } else {
                    UIUtils.showTips(LoginActivity.this, "请输入账户信息");
                }
                break;
        }
    }

    private String getDeviceToken() {
        String deviceToken = PushAgent.getInstance(LoginActivity.this).getRegistrationId();
        return TextUtils.isEmpty(deviceToken) ? "" :deviceToken;

    }

    private void httpLogin() {
        showLoading();
        HttpRequest httpRequest = new HttpRequest(Request.Method.POST, Utils.login,
                this) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("sn", binding.editNum.getText().toString());
                map.put("password", binding.editPwd.getText().toString());
                map.put("deviceToken", getDeviceToken());
                return map;
            }
        };
        requestQueue.add(httpRequest);
    }

    private boolean checkInput() {
        return !TextUtils.isEmpty(binding.editNum.getText().toString()) && !TextUtils.isEmpty(binding.editPwd.getText().toString());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RegisterSucEvent event) {
        finish();
    }

    @Override
    public void onSuccess(String id, String resp) {
        LoginResp loginResp = new Gson().fromJson(resp, LoginResp.class);
        if (Utils.parseData(loginResp)) {
            //存储登录信息
            Utils.saveData(LoginActivity.this, Utils.LOGIN_DATA, resp);
            Utils.saveData(LoginActivity.this, Utils.PWD, binding.editPwd.getText().toString());
            Utils.registerResp = loginResp;
            startActivity(new Intent(LoginActivity.this, HospitalMainActivity.class));
            finish();
        } else {
            UIUtils.showToast(LoginActivity.this, loginResp.getMsg());
        }
        dismissLoading();
    }

    @Override
    public void onError(String error) {
        dismissLoading();
        UIUtils.showToast(LoginActivity.this, error);
    }
}
